package com.zhz.order.config;

import org.redisson.Redisson;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Component;

/**
 * @program: idempotent_redis
 * @description: 通过红锁, 实现了master突然挂掉, 导致锁失效问题
 * @author: zhanghz001
 * @create: 2021-03-16 13:31
 **/
@Component
public class RedissonRedLockConfig {
    
    public RedissonRedLock initRedissonClient(String lockKey) {
        //因为 Redlock 算法要求至少N/2+1 个节点都加锁成功，才算最终的锁申请成功
        //配置config类,和RedissonClient
        Config config1 = new Config();
        config1.useSingleServer().setAddress("redis://192.168.23.129:6501").setDatabase(0);
        RedissonClient redissonClient1 = Redisson.create(config1);
        Config config2 = new Config();
        config2.useSingleServer().setAddress("redis://192.168.23.129:6506").setDatabase(0);
        RedissonClient redissonClient2 = Redisson.create(config2);
        Config config3 = new Config();
        config3.useSingleServer().setAddress("redis://192.168.23.129:6507").setDatabase(0);
        RedissonClient redissonClient3 = Redisson.create(config3);
        Config config4 = new Config();
        config4.useSingleServer().setAddress("redis://192.168.23.129:6508").setDatabase(0);
        RedissonClient redissonClient4 = Redisson.create(config4);
        Config config5 = new Config();
        config5.useSingleServer().setAddress("redis://192.168.23.129:6509").setDatabase(0);
        RedissonClient redissonClient5 = Redisson.create(config5);
        
        //获取锁
        RLock rLock1 = redissonClient1.getLock(lockKey);
        RLock rLock2 = redissonClient2.getLock(lockKey);
        RLock rLock3 = redissonClient3.getLock(lockKey);
        RLock rLock4 = redissonClient4.getLock(lockKey);
        RLock rLock5 = redissonClient5.getLock(lockKey);
        //红锁
        RedissonRedLock redissonRedLock = new RedissonRedLock(rLock1, rLock2, rLock3, rLock4, rLock5);
        return redissonRedLock;
    }
}
